import React, { useState, useEffect } from 'react';
import { Upload } from 'antd';
import ImgCrop from 'antd-img-crop';
import { getDictList4Type } from '@/services/system/dict';

// 定义传参
interface UserPhotoUploadParams {
  onRender?: (item: any) => {};
  photo?: {
    select?: boolean;
    key?: number;
    fontColor?: string;
    fontValue?: string;
    background?: string;
    upload?: boolean;
    photoUrl?: string;
  };
}

/**
 * 用户头像上传
 *
 * @author zhangby
 * @date 25/9/20 3:21 pm
 */
const UserPhotoUpload: React.FC<UserPhotoUploadParams> = (props) => {
  const { onRender, photo } = props;
  const [fileList, setFileList] = useState([]);
  const [uploadUrl, setUploadUrl] = useState();

  // 初始化
  useEffect(() => {
    getDictList4Type('upload_config').then((res) => {
      if (res) {
        const dictMap = res.result?.filter((item) => item.label === 'img_upload_url')[0];
        if (dictMap) {
          setUploadUrl(dictMap.value);
        }
        // 刷新
        const visitMap = res.result?.filter((item) => item.label === 'img_visit_url')[0];
        if (visitMap) {
          // 格式化
          if (photo.photoUrl) {
            setFileList([
              {
                uid: '-1',
                name: 'upload.png',
                status: 'done',
                url: visitMap.value + photo.photoUrl,
              },
            ]);
          }
        }
      }
    });
  }, []);

  // 上传
  // @ts-ignore
  const onChange = (file) => {
    const { fileList: newFileList } = file;
    // 循环
    newFileList.forEach((img: any) => {
      const { response } = img;
      if (response) {
        if (response.code === '000') {
          const { result } = response;
          if (result) {
            img['url'] = result.url;
            img['status'] = result.status;
          }
        }
      }
    });
    setFileList(newFileList);
    // 同步刷新
    const url = newFileList.length > 0 ? newFileList[0].url : '';
    // 回调
    const result = { select: false, upload: true, photoUrl: url };
    if (onRender) {
      onRender(result);
    }
  };

  // 用户上传
  return (
    <>
      <div style={{ marginLeft: 275 }}>
        <ImgCrop rotate>
          <Upload
            action={uploadUrl}
            headers={{
              Authorization: localStorage.getItem('token'),
            }}
            listType="picture-card"
            showUploadList={{
              showPreviewIcon: false,
            }}
            fileList={fileList}
            onChange={onChange}
          >
            {fileList.length < 1 && '+ Upload'}
          </Upload>
        </ImgCrop>
      </div>
    </>
  );
};

export default UserPhotoUpload;
